package com.lingtianyu.tech.erbaoshen.core.provider.bean.registry;

import com.lingtianyu.tech.erbaoshen.core.provider.bean.annotation.ErBaoShenService;
import com.lingtianyu.tech.erbaoshen.core.provider.bean.annotation.Service;
import com.lingtianyu.tech.erbaoshen.core.util.ErBaoShenFinals;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

@Slf4j
public class ErBaoShenBeanRegistriesFactory implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {

    private ResourceLoader resourceLoader;
    private ClassLoader classLoader;
    private Environment environment;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
        scanner.setResourceLoader(this.resourceLoader);
        scanner.addIncludeFilter(new AnnotationTypeFilter(ErBaoShenService.class));
        scanner.addIncludeFilter(new AnnotationTypeFilter(Service.class));
        String property = environment.getProperty(ErBaoShenFinals.PROPERTIES_SCAN);
        if(property == null || property.isEmpty()) {
            throw new RuntimeException(ErBaoShenFinals.PROPERTIES_SCAN + " is null");
        }
        String[] split = property.split(",");
        scanner.scan(split);
    }
}
